package com.younion.action.consumer.impl;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.younion.action.consumer.AbstractRequestConsumer;
import com.younion.action.interactive.mobile.ApiConstant;
import com.younion.action.interactive.mobile.ResultObject;
import com.younion.business.IRegisterUserService;
import com.younion.model.LoginResult;
import com.younion.util.HttpRequestUtils;
import com.younion.util.JsonUtils;
import com.younion.util.MD5;
import com.younion.vo.RegisterUserVO;

public class RegisterConsumer extends AbstractRequestConsumer {
	private IRegisterUserService registerUserService;

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return register(request, response);
	}

	public String register(HttpServletRequest request, HttpServletResponse response) {
		String login_id = request.getParameter("login_id");
		String password = request.getParameter("password");
		LoginResult loginResult = new LoginResult();
		ResultObject resultObject = new ResultObject();

		RegisterUserVO registerUserVO = new RegisterUserVO();
		registerUserVO.setLoginId(login_id);
		registerUserVO.setPassword(password);
		registerUserVO.setStatus(ApiConstant.APP_USER_DEFAULT_STATUS);
		try {
			Map paramMap = new HashMap();
			paramMap.put("loginId", login_id);
			int registCount = registerUserService.getCountByMap(paramMap);
			if (registCount == 0) {
				registerUserService.save(registerUserVO);
				loginResult.setType(ApiConstant.APP_USER_FLAG);
				loginResult.setUser_integral("0");
				loginResult.setUser_name(login_id);
				loginResult.setUser_token(MD5.getMD5((login_id + password)
						.getBytes("utf-8")));
				resultObject.setStatus(ApiConstant.SUCCESS_STATUS);
				resultObject.setResult(loginResult);
			} else {
				resultObject.setStatus(ApiConstant.FALSE_STATUS);
				resultObject.setResult(loginResult);
				resultObject.setMsg(ApiConstant.REGIS_EXISTS_USER);
			}
		} catch (Exception e) {
			resultObject.setStatus(ApiConstant.FALSE_STATUS);
			resultObject.setMsg(ApiConstant.PUBLIC_EXCEPTION);
			e.printStackTrace();
		}
		HttpRequestUtils.printContent(JsonUtils.parseObj2Json(resultObject),
				response);
		return null;
	}

	public void setRegisterUserService(IRegisterUserService registerUserService) {
		this.registerUserService = registerUserService;
	}

}
